package com.lanyun.framework.shiro.realm;

import com.lanyun.framework.shiro.realm.token.CustomToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 *@Description 根据不同的领域获取不同的认证信息
 *@Author Jack.Zou
 *@Date 2021/7/13 23:08
 *@since:
 *@copyright:  版权所有2022 开源组织 gitee(https://gitee.com/walster)作者：Jack.Zou<br/>
 *            
 */
public class LanYunModularRealmAuthenticator extends ModularRealmAuthenticator {

    /**
     * 通过获取不同的loginType来判断进入某一个realm
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        //做Realm的一个校验
        assertRealmsConfigured();
        //获取前端传递过来的token
        CustomToken customToken=(CustomToken)authenticationToken;
        String loginType = customToken.getLoginType();
        //获取所有的realms()
        Collection<Realm> realms = getRealms();
        Collection<Realm> typeRealms=new ArrayList<>();
        for (Realm realm:realms){
            if(realm.getName().equals(loginType)){
                typeRealms.add(realm);
            }
        }
        if(typeRealms.size()==1){
            return doSingleRealmAuthentication(typeRealms.iterator().next(),customToken);
        }else{
            return doMultiRealmAuthentication(typeRealms,customToken);
        }
    }

}
